<template>
  <!-- 聊天组件 -->
  <div class="chat">
    <NavBar :title="targetUser?.userNickname || '聊天'" backgroundColor="#161622">
      <template #left>
        <div class="left" @click="handleClick">
          <Icon name="zuojiantou" size="18" color="#fff"></Icon>
        </div>
      </template>
    </NavBar>
    <!-- 聊天列表内容 -->
    <div class="chat_list">
      <!-- 遍历所有消息 -->
      <div v-for="msg in chatList" :key="msg._id || msg.createdAt" class="chat_item">
        <!-- 显示时间 -->
        <div v-if="msg.showTime" class="time">
          {{ formatTime(msg.createdAt).formatted }}
        </div>

        <!-- 左侧消息（对方发的） -->
        <div v-if="msg.fromId !== userId" class="item_left">
          <div class="avatar">
            <img :src="targetUser?.userAvatar" loading="lazy" alt="">
          </div>
          <div class="content">
            <div class="text">{{ msg.privateLetterContent || msg.content }}</div>
          </div>
        </div>

        <!-- 右侧消息（我发的） -->
        <div v-else class="item_right">
          <div class="content">
            <div class="text">{{ msg.privateLetterContent || msg.content }}</div>
          </div>
          <div class="avatar">
            <img :src="targetUser?.userAvatar" loading="lazy" alt="">
          </div>
        </div>
      </div>
    </div>
    <div class="input_bar">
      <input type="text" ref="InputFocus" placeholder="发送消息..." v-model="inputContent">
      <div class="input_bar_icon">
        <Icon name="aite" size="18" color="#fff" />
      </div>
      <div class="input_bar_icon" @click="sendMessage">
        <Icon name="dui" size="18" color="#fff" />
      </div>
    </div>
  </div>
</template>

<script setup>
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import { useDateFormat } from '@/composables/useDateFormat'


// 引入 socket.io 插件
import { useRouter } from 'vue-router'
import { computed, onMounted, ref, nextTick, inject } from 'vue'
const socket = inject('socket')


import { getChatListAPI } from '@/api/message'
import { useUserIDStore } from '@/stores/UserID'
const userIDStore = useUserIDStore()
const userId = userIDStore.userInfo?.userId



// 路由
const router = useRouter()

// 返回消息页
const handleClick = () => {
  router.push({ name: 'contact' })
}

// 获取要聊天的用户
import { useChatStore } from '@/stores/userChat'
const chatStore = useChatStore()
// 要聊天的用户
const targetUser = computed(() => chatStore.targetUser)


// 聊天列表
const chatList = ref([])
const leftChatList = ref([])
const rightChatList = ref([])

const getChatList = async () => {
  try {
    const res = await getChatListAPI(userId, targetUser.value.userId)
    if (res.code === 200) {
      leftChatList.value = []
      rightChatList.value = []

      // 分类
      res.data.forEach(msg => {
        if (msg.fromId === userId) {
          rightChatList.value.push(msg)
        } else {
          leftChatList.value.push(msg)
        }
      })

      // 排序
      leftChatList.value.sort((a, b) => a.createdAt - b.createdAt)
      rightChatList.value.sort((a, b) => a.createdAt - b.createdAt)

      // 合并所有消息，并按时间排序
      chatList.value = [...leftChatList.value, ...rightChatList.value]
        .sort((a, b) => a.createdAt - b.createdAt)

      // 添加 showTime 字段：只有当与上一条时间不同时才显示
      chatList.value.forEach((msg, index) => {
        msg.showTime = index === 0 ||
          !isSameDayAndHour(chatList.value[index - 1].createdAt, msg.createdAt)
      })
      // ✅ 数据更新后，滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error)
  }
}
const isSameDayAndHour = (time1, time2) => {
  const d1 = new Date(time1)
  const d2 = new Date(time2)
  return d1.getDate() === d2.getDate() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getFullYear() === d2.getFullYear() &&
    d1.getHours() === d2.getHours()
}
const formatTime = (timestamp) => {
  return useDateFormat(timestamp, 'YYYY-MM-DD HH:mm', { relative: true })
}
onMounted(() => {
  getChatList()
  socket.on('receivePrivateLetter', (data) => {
    console.log('📢 收到实时消息:', data)

    // ✅ 只处理发给当前用户、来自目标用户的私信
    if (data.toId === userId && data.fromId === targetUser.value.userId) {
      chatList.value.push(data)

      // ✅ 排序
      chatList.value.sort((a, b) => a.createdAt - b.createdAt)

      // ✅ 更新时间显示
      updateShowTime()

      // ✅ 滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    }
  })
})


// 发送消息
import { sendMessageAPI } from '@/api/message'
const InputFocus = ref(null)
const inputContent = ref('')
const sendMessage = async () => {
  const content = inputContent.value.trim()
  if (!content) return

  try {
    const res = await sendMessageAPI(userId, targetUser.value.userId, content)

    // ✅ 后端返回的是单个对象，不是数组
    const newMsg = res.data
    // 2. 再通过 socket 告诉后端“转发这条消息”
    socket.emit('sendPrivateLetter', {
      ...newMsg,
      content: newMsg.content || newMsg.privateLetterContent
    }) // 或只传必要字段

    // ✅ 添加到 chatList
    chatList.value.push(newMsg)

    // ✅ 排序：按 createdAt 升序
    chatList.value.sort((a, b) => a.createdAt - b.createdAt)

    // ✅ 更新 showTime 字段（只显示时间差大于1小时的消息）
    updateShowTime()

    // ✅ 清空输入框
    inputContent.value = ''

    // ✅ 数据更新后，滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    console.error('发送失败:', error)
  }
}
const updateShowTime = () => {
  chatList.value.forEach((msg, index) => {
    msg.showTime = index === 0 ||
      !isSameDayAndHour(chatList.value[index - 1].createdAt, msg.createdAt)
  })
}

const scrollToBottom = () => {
  const chatListEl = document.querySelector('.chat_list')
  if (chatListEl) {
    // 使用 smooth 滚动更自然（可选）
    chatListEl.scrollTo({
      top: chatListEl.scrollHeight,
      behavior: 'smooth' // 或 'auto'（默认）
    })
  }
}
</script>

<style lang="scss" scoped>
.chat_list {
  width: 100%;
  height: calc(100vh - 90px);
  overflow: auto;
  padding: 10px 8px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background-color: #161622;
  z-index: 2025;

  &::-webkit-scrollbar {
    width: 0;
    height: 0;
  }

  .chat_item {
    display: flex;
    flex-direction: column;
    gap: 5px;
    text-align: center;
    margin-bottom: 10px;

    .time {
      font-size: 12px;
      color: #fff;
      font-weight: bold;
    }

    .item_left,
    .item_right {
      position: relative;
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 5px 10px;
      border-radius: 5px;
      flex: 1;
      /* 关键：撑满空间 */
      // max-width: calc(100% - 60px);
      /* 防止过长 */
      overflow: hidden;
      /* 防止内容溢出 */
    }

    .item_left .content::before {
      display: block;
      position: absolute;
      top: 20px;
      left: -18px;
      border: 8px solid transparent;
      border-right: 14px solid #fff;
      content: '';
      // 旋转
      transform: rotate(-20deg);
      z-index: 22;
    }

    .item_right .content::before {

      display: block;
      position: absolute;
      top: 20px;
      right: -18px;
      border: 8px solid transparent;
      border-left: 14px solid #fff;
      content: '';
      // 旋转
      transform: rotate(20deg);
      z-index: 22;
    }


    .item_left {
      margin-right: auto;
    }

    .item_right {
      margin-left: auto;


    }

    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
        /* 图片不拉伸变形 */
      }
    }

    .content {
      position: relative;
      display: flex;
      flex-direction: column;
      gap: 5px;
      padding: 10px;
      border-radius: 5px;
      background-color: #fff;
      font-size: 14px;
      font-weight: bold;
      color: #000;
      white-space: pre-wrap;
      min-width: 30px;
      word-break: break-all;
      text-align: left;
      // 最小高度
      min-height: 40px;
    }
  }
}

.input_bar {
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  height: 44px;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 2025;
  background: #1a1b20;
  border-top: 1px solid #292825cc;

  input {
    background: #1a1b20;
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    font-size: 14px;
    color: #e8e8e9;
    padding-left: 10px;
    caret-color: #face15;
  }

  .input_bar_icon {
    width: 44px;
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;

  }
}
</style>